package cn.imvc.util;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import cn.imvc.core.HttpContext;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExcelUtils {
	/**
	 * 
	 * @param headline  标题行
	 * @param contents	内容//第一个参数是列，第二个参数是行
	 * @param fileName	文件名
	 * @throws IOException
	 * @throws RowsExceededException
	 * @throws WriteException
	 */
	public static void createExcel(String[] headline,String[][] contents,String fileName) throws IOException, RowsExceededException, WriteException{
		HttpServletResponse response = HttpContext.getResponse();
		OutputStream os = response.getOutputStream();//取得输出流
		response.reset();//清空输出流 
		//下面是对中文文件名的处理
		response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1")+".xls");
		response.setContentType("application/msexcel");//定义输出类型
        //创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(os);
        //创建新的一页
        WritableSheet sheet = workbook.createSheet("First Sheet",0);
        //创建要显示的内容,创建一个单元格，第一个参数为列坐标，第二个参数为行坐标，第三个参数为内容
        //添加标题
        for (int i = 0; i < headline.length; i++) {
        	sheet.addCell(new Label(i, 0, headline[i]));
        	sheet.setColumnView(i,20);
        }
        //添加内容
		for (int row = 0; row < contents[0].length; row++) {
			for (int i = 0; i < headline.length; i++) {
				sheet.addCell(new Label(i, row+1, contents[i][row]));
			}
		}
		 //把创建的内容写入到输出流中，并关闭输出流
        workbook.write();
        workbook.close();
        os.close();
	}
}
